package com.cxf.cxfknife4j.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * description: LoginInterceptor <br>
 * date: 2022/3/9 21:16 <br>
 * author: cxf <br>
 * version: 1.0 <br>
 */
//@Component
public class LoginInterceptor implements HandlerInterceptor {}/*{
    //方法执行前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        //判断前端是否传来token如果没传进行拦截
        String token=request.getHeader("token");//从http请求头中获取token

        System.out.println("handler:"+handler);

        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod handlerMethod=(HandlerMethod)handler;

        PassToken handlePass = handlerMethod.getBean().getClass().getDeclaredAnnotation(PassToken.class);
        System.out.println("拿到的handlePass“"+handlePass);
        System.out.println("handle拿到的类是："+handlerMethod.getBean().getClass().getName());
        System.out.println("handle拿到的类是否是swagger的控制器类："+handlerMethod.getBean().getClass().getName().equals("springfox.documentation.swagger.web.ApiResourceController"));

        //判断如果请求的类是swagger的控制器，直接通行。
        if(handlerMethod.getBean().getClass().getName().equals("springfox.documentation.swagger.web.ApiResourceController")){
            return  true;
        }

        if(null != handlePass){
            System.out.println("类上带PassToken注解，直接通行");
            return true;
        }else {
            Method method=handlerMethod.getMethod();
            //检查是否有@passtoken注解，有则跳过验证
            if(method.isAnnotationPresent(PassToken.class))
            {
                PassToken passToken=method.getAnnotation(PassToken.class);
                if(passToken.required())
                {
                    //方法带passToken直接通行
                    System.out.println("方法带passToken直接通行");
                    return  true;
                }else {
                    System.out.println("方法没有带passToken，进行token验证");
                    //判断token是否过期
                    if(token!=null)
                    {
                        Claims claims = JWTUtil.parseJWT(token);
                        //解析token判断是否过期
                        if(claims!=null) {
                            long expTime = Long.parseLong(claims.get("ExpTime").toString());
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date nowDate = new Date();
                            Date expDate = new Date(expTime);
                            String nowDateStr = sdf.format(nowDate);
                            String expDateStr=sdf.format(expDate);
                            if (nowDate.getTime() >= expDate.getTime()) {
                                response.setContentType("json/html; charset=utf-8");
                                //response.sendError(HttpServletResponse.SC_FORBIDDEN,"用户无权限,请登录");
                                PrintWriter printWriter = response.getWriter();
                                Map<String, String> resultError = new HashMap<>();
                                resultError.put("code", "403");
                                resultError.put("message", "Token已过期，请重新登录");
                                Object ces = JsonUtil.objectToString(resultError);
                                printWriter.write(ces.toString());
                                return false;
                            }
                            else
                            {
                                //把当前登录信息保存到threadLocal
                                LocalThreadRelUserInfo localThreadRelUserInfo=new LocalThreadRelUserInfo();
                                localThreadRelUserInfo.setUserId(Long.parseLong(claims.get("UserId").toString()));
                                localThreadRelUserInfo.setUserName(claims.get("UserName").toString());
                                LocalThreadRelUser.set(localThreadRelUserInfo);
                            }
                        }
                        else
                        {
                            response.setContentType("json/html; charset=utf-8");
                            //response.sendError(HttpServletResponse.SC_FORBIDDEN,"用户无权限,请登录");
                            PrintWriter printWriter = response.getWriter();
                            Map<String, String> resultError = new HashMap<>();
                            resultError.put("code", "403");
                            resultError.put("message", "Token已过期，请重新登录");
                            Object ces = JsonUtil.objectToString(resultError);
                            printWriter.write(ces.toString());
                            return false;
                        }
                    }else {
                        //提示无权限访问
                        response.setContentType("json/html; charset=utf-8");
                        //response.sendError(HttpServletResponse.SC_FORBIDDEN,"用户无权限,请登录");
                        PrintWriter printWriter=response.getWriter();
                        Map<String,String> resultError=new HashMap<>();
                        resultError.put("code","403");
                        resultError.put("message","用户无权限访问,请登录");
                        Object ces = JsonUtil.objectToString(resultError);
                        printWriter.write(ces.toString());
                        return false;
                    }
                }
            }else {
                System.out.println("方法没有带passToken，进行token验证");
                //判断token是否过期
                if(token!=null)
                {
                    Claims claims = JWTUtil.parseJWT(token);
                    //解析token判断是否过期
                    if(claims!=null) {
                        long expTime = Long.parseLong(claims.get("ExpTime").toString());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date nowDate = new Date();
                        Date expDate = new Date(expTime);
                        String nowDateStr = sdf.format(nowDate);
                        String expDateStr=sdf.format(expDate);
                        if (nowDate.getTime() >= expDate.getTime()) {
                            response.setContentType("json/html; charset=utf-8");
                            //response.sendError(HttpServletResponse.SC_FORBIDDEN,"用户无权限,请登录");
                            PrintWriter printWriter = response.getWriter();
                            Map<String, String> resultError = new HashMap<>();
                            resultError.put("code", "403");
                            resultError.put("message", "Token已过期，请重新登录");
                            Object ces = JsonUtil.objectToString(resultError);
                            printWriter.write(ces.toString());
                            return false;
                        }
                        else
                        {
                            //把当前登录信息保存到threadLocal
                            LocalThreadRelUserInfo localThreadRelUserInfo=new LocalThreadRelUserInfo();
                            localThreadRelUserInfo.setUserId(Long.parseLong(claims.get("UserId").toString()));
                            localThreadRelUserInfo.setUserName(claims.get("UserName").toString());
                            LocalThreadRelUser.set(localThreadRelUserInfo);
                        }
                    }
                    else
                    {
                        response.setContentType("json/html; charset=utf-8");
                        //response.sendError(HttpServletResponse.SC_FORBIDDEN,"用户无权限,请登录");
                        PrintWriter printWriter = response.getWriter();
                        Map<String, String> resultError = new HashMap<>();
                        resultError.put("code", "403");
                        resultError.put("message", "Token已过期，请重新登录");
                        Object ces = JsonUtil.objectToString(resultError);
                        printWriter.write(ces.toString());
                        return false;
                    }
                }else {
                    //提示无权限访问
                    response.setContentType("json/html; charset=utf-8");
                    //response.sendError(HttpServletResponse.SC_FORBIDDEN,"用户无权限,请登录");
                    PrintWriter printWriter=response.getWriter();
                    Map<String,String> resultError=new HashMap<>();
                    resultError.put("code","403");
                    resultError.put("message","用户无权限访问,请登录");
                    Object ces = JsonUtil.objectToString(resultError);
                    printWriter.write(ces.toString());
                    return false;
                }
            }
        }
        return true;// 只有返回true才会继续向下执行，返回false取消当前请求
    }

    //方法执行结束后
    @Override
    public   void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                  @Nullable Exception ex) throws Exception {
        //清楚掉线程保存的用户信息
        LocalThreadRelUser.remove();
    }
}*/
